/*
 * @Author: wuqingchun
 * @Date: 2024-07-29 14:37:26
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-07-31 17:33:11
 */

#include <string.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>

#include "ev_dispatcher.h"
#include "ev_event.h"
#include "ev_util.h"
#include "ev_log.h"
#include "ev_signal.h"

int g_iEVSignalWriteFd = -1;


static void __signal_Handler(int iSigNo)
{
    int iSaveErrno = errno;

    LOG_INFO("__signal_Handler, %d", iSigNo);

    unsigned char ucMsg = (unsigned char)iSigNo;
    ssize_t lLen;
    do
    {
        lLen = write(g_iEVSignalWriteFd, &ucMsg, sizeof(ucMsg));
    } while (lLen <= 0 && errno == EINTR);
    
    errno = iSaveErrno;
}

static int __signal_SetHandler(int iSigNo,  void (*handler)(int))
{
    struct sigaction stSigAct;

    memset(&stSigAct, 0, sizeof(stSigAct));
    stSigAct.sa_handler = handler;
    sigfillset(&stSigAct.sa_mask);

    int iErr = sigaction(iSigNo, &stSigAct, NULL);
    if (iErr == -1)
    {
        LOG_ERROR("sigaction");
        return -1;
    }

    LOG_INFO("sigaction, %d", iSigNo);

    return 0;
}

static void __signal_EventCB(int iFd, void* pArg)
{
    static unsigned char aucSignals[1024];
    ssize_t lLen = 0;

    EV_DISPATCHER_S* pstDP = pArg;

    lLen = read(iFd, aucSignals, sizeof(aucSignals));

    LOG_INFO("__signal_EventCB");

    EV_EVENT_S* pstEvent = pstDP->apstEvent[0];
    pstDP->apstEvent[0]->pfCallback(pstEvent->iEventFd, pstEvent);
}


int EV_signal_Add(int iSigNo)
{
    __signal_SetHandler(iSigNo, __signal_Handler);
}

int EV_signal_Delete()
{

}

int EV_signal_Init(EV_DISPATCHER_S* pstDP)
{
    int iErr = EV_util_CreatePairFd(pstDP->aiPairFd);
    if (iErr == -1)
    {
        LOG_ERROR("CreatePairFd, %s", strerror(errno));
        return iErr;
    }

    LOG_INFO("Pair fd, %d:%d\n", pstDP->aiPairFd[0], pstDP->aiPairFd[1]);

    g_iEVSignalWriteFd = pstDP->aiPairFd[1];
    pstDP->stSigEvent.pfCallback = __signal_EventCB;
    pstDP->stSigEvent.iEventFd = pstDP->aiPairFd[0];

    return 0;
}
